package com.user.query.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.user.query.model.AdminArea;
import com.user.query.model.Menu;
import com.user.query.model.Role;
import com.user.query.model.User;
import com.user.query.service.AdminAreaService;
import com.user.query.service.MenuService;
import com.user.query.service.RoleService;
import com.user.query.service.UserService;
import com.user.query.utils.ConstantUtils;
import com.user.query.utils.EncryptUtils;
import com.user.query.utils.FileUtils;
import com.user.query.utils.HttpCode;
import com.user.query.utils.IDGenerator;
import com.user.query.utils.Page;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private AdminAreaService adminAreaService;
	@Resource
	private MenuService menuService;
	@Resource
	private RoleService roleService;
	/**
	 * 
	 * 方法含义：用户登录
	 * 
	 * @author bgt
	 * @return
	 * @date 2015-11-30
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request,
			@RequestParam("userName") String username,
			@RequestParam("password") String psw) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			HttpSession session = request.getSession();
			User user = userService.getUserByAccountNoAndPsw(username,
					EncryptUtils.encrypt(psw));
			if (user != null && user.getIsDel() != 0
					&& user.getRoleId() != null) {
				session.setAttribute(ConstantUtils.USERINFO, user);
				map.put("code", HttpCode.HTTP_CODE_200);
				map.put("msg", "登录成功！");
			} else {
				map.put("code", HttpCode.HTTP_CODE_400);
				map.put("msg", "用户名或密码错误！");
			}
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "登录异常！");
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 
	 * 方法含义：添加用户初始化
	 * 
	 * @author bgt
	 * @return
	 * @date 2015-12-1
	 */
	@RequestMapping("/addUserInit")
	public String init(HttpServletRequest request, ModelMap map) {
		try {
			int level = 2;
			// 2级区域
			List<AdminArea> adminAreas = adminAreaService
					.findAllByLevel2(level);
			map.put("adminAreas", adminAreas);
			// 角色
			List<Role> roles2=null;
			User user=getCurrentUser(request);
			if(user.getRoleId().equals(ConstantUtils.RoleType.PGLY)){
				int[] levels={1,2,3,4};
				roles2=roleService.findByLevels(levels);
			}else{
				int[] levels={2,3,4};
				roles2=roleService.findByLevels(levels);
			}
			map.put("roles", roles2);
			map.put("code", HttpCode.HTTP_CODE_200);
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "添加用户初始化数据失败！");
			log.error("添加用户初始化数据失败！", e);
		}
		return "user/AddUser";
	}

	/**
	 * 
	 * 方法含义：用户添加
	 * 
	 * @author bgt
	 * @return
	 * @date 2015-12-1
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> add(HttpServletRequest request, User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		User pu = getCurrentUser2(request);
		try {
			if (user != null && StringUtils.isNotBlank(user.getAccountNo())) {
				User u = userService.findByAccountNo(user.getAccountNo());
				if (u != null) {
					map.put("code", HttpCode.HTTP_CODE_400);
					map.put("msg", "此用户名已存在，请更换！");
					return map;
				} else {
					user.setUserId(IDGenerator.getUUID());
					user.setCreator(pu.getUserId());
					user.setPassword(EncryptUtils.encrypt(user.getPassword()));
					if (StringUtils.isBlank(user.getRoleId())) {
						user.setRoleId("0056ee85505f40f399186cc724cdc7bb");// 普通用户
					}
					user.setIsDel(1);
					userService.insert(user);
					map.put("code", HttpCode.HTTP_CODE_200);
				}
			} else {
				map.put("code", HttpCode.HTTP_CODE_400);
				map.put("msg", HttpCode.HTTP_MSG_400);
			}
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "添加用户失败！");
			log.error("添加用户失败！", e);
		}
		return map;
	}

	/**
	 * @Description: 查询用户列表
	 * @author bgt
	 * @date 2015121
	 */
	@RequestMapping("/managerList")
	public String managerList(HttpServletRequest request,
			@RequestParam(defaultValue = "1", required = false) Integer pageNo,
			@RequestParam(defaultValue = "10", required = false) Integer pageSize,
			@RequestParam(value = "keyWord", required = false) String keyWord,
			@RequestParam(value = "areano", defaultValue="0",required = false) String areano,
			@RequestParam(value = "status", defaultValue="-1",required = false) Integer status,
			ModelMap map) {
		try {
			if(status==-1){
				status=null;
			}
			User p = getCurrentUser2(request);
			Page page = new Page();
			page.setPageNo(pageNo);
			page.setPageSize(pageSize);
			String roleId = p.getRoleId();
			String isCity = null;
			// 省管理员
			if (roleId.equals(ConstantUtils.RoleType.PGLY)) {
				int level = 2;
				// 2级区域
				List<AdminArea> adminAreas = adminAreaService
						.findAllByLevel2(level);
				map.put("adminAreas", adminAreas);
				if(areano.equals("0")){
					isCity=null;
				}else{
					isCity =areano;
				}
			}
			// 市管理员
			if (roleId.equals(ConstantUtils.RoleType.CGJY)) {
				isCity = p.getCity();
			}
			int count = userService.countManagerUsers(isCity, keyWord, status,
					page);
			if (count > 0) {
				List<User> users = userService.selectManagerUsers(isCity,
						keyWord, status, page);
				for (int i = 0; i < users.size(); i++) {
					if (StringUtils.isNotBlank(users.get(i).getCity())) {
						users.get(i).setCityName(
								adminAreaService.findByAreaNo(
										users.get(i).getCity()).getAreaName());
					}
					if (StringUtils.isNotBlank(users.get(i).getCounty())) {
						users.get(i)
								.setCountyName(
										adminAreaService.findByAreaNo(
												users.get(i).getCounty())
												.getAreaName());
					}
				}
				map.put("users", users);
			}
			page.setTotalRecord(count);

			if (StringUtils.isNotBlank(keyWord)) {
				map.put("keyWord", keyWord);
			}
			if (status != null) {
				map.put("status", status);
			}
			if (areano != null) {
				map.put("areano", areano);
			}

			map.put("page", page);
			map.put("code", HttpCode.HTTP_CODE_200);
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "查询前台用户列表失败！");
			log.error("查询前台用户列表失败！", e);
		}
		return "user/UserList";
	}

	/**
	 * 
	 * @Description: 禁用启用 status 1启用 0禁用
	 * @author bgt
	 * @date 2015-10-28 下午2:43:32
	 */
	@RequestMapping("/status")
	@ResponseBody
	public Map<String, Object> status(HttpServletRequest request,
			@RequestParam(value = "userId") String userId,
			@RequestParam(value = "status") Integer status) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			User user = new User();
			user.setUserId(userId);
			user.setIsDel(status);
			userService.updateByPrimaryKeySelective(user);
			map.put("code", HttpCode.HTTP_CODE_200);
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "更新用户状态失败！");
			log.error("更新用户状态失败！", e);
		}
		return map;
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param oldPsw
	 * @param newPsw
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/updatePsw")
	@ResponseBody
	public Map<String, Object> updatePsw(HttpServletRequest request,
			@RequestParam("oldpsw") String oldPsw,
			@RequestParam("newpsw") String newPsw) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			HttpSession session = request.getSession();
			User user = (User) request.getSession().getAttribute(
					ConstantUtils.USERINFO);
			if (user != null) {
				String oldPswMd5 = EncryptUtils.encrypt(oldPsw);
				String newPswMd5 = EncryptUtils.encrypt(newPsw);
				if (user.getPassword().equals(oldPswMd5)) {
					userService.updatePsw(user.getUserId(), newPswMd5);
					user.setPassword(newPswMd5);
					session.setAttribute(ConstantUtils.USERINFO, user);
					map.put("code", HttpCode.HTTP_CODE_200);
				} else {
					map.put("code", HttpCode.HTTP_CODE_400);
					map.put("msg", "旧密码错误！");
				}
			} else {
				map.put("code", HttpCode.HTTP_CODE_401);
				map.put("msg", HttpCode.HTTP_MSG_401);
			}
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", HttpCode.HTTP_MSG_500);
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * @Description: 密码重置功能
	 * @author bgt
	 * @date 2015-10-28 下午2:50:27
	 */
	@RequestMapping("/resetPwd")
	@ResponseBody
	public Map<String, Object> resetPwd(HttpServletRequest request,
			@RequestParam(value = "userId") String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			User user = new User();
			user.setUserId(userId);
			user.setPassword(EncryptUtils.encrypt(ConstantUtils.RESETPWD));
			userService.updateByPrimaryKeySelective(user);
			map.put("code", HttpCode.HTTP_CODE_200);
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "更新用户状态失败！");
			log.error("更新用户状态失败！", e);
		}
		return map;
	}

	/**
	 * 
	 * @Description: 用户注销
	 * @author bgt
	 * @date 2015-10-29 上午9:04:20
	 */
	@RequestMapping("/Logout")
	@ResponseBody
	public Map<String, Object> adminLogout(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			HttpSession session = request.getSession();
			User user = getCurrentUser2(request);
			session.removeAttribute(ConstantUtils.USERINFO);
			map.put("code", HttpCode.HTTP_CODE_200);
			map.put("msg", HttpCode.HTTP_MSG_200);
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", HttpCode.HTTP_MSG_500);
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * @Description: 根据USERID查询该用户信息 
	 * @author  bgt
	 * @date 2015-10-28 下午2:59:54
	 */
	@RequestMapping("/userDetais/{userId}/{jump}")
	public String userDetais(HttpServletRequest request,
			@PathVariable(value="userId")String userId,
			@PathVariable(value="jump")Integer jump,ModelMap map){
		
		try {
			
			User user = userService.selectByPrimaryKey(userId);
			map.put("user", user);
			
			
			int level = 2;
			//2级区域
			List<AdminArea> adminAreas = adminAreaService.findAllByLevel2(level);
			map.put("adminAreas", adminAreas);
			//角色  根据当前用户查询
			/*List<Role> roles = new ArrayList<Role>();
			Role r1 = new Role();
			r1.setRoleId("0056ee85505f40f399186cc724cdc7b1");
			r1.setRoleLevel(2);
			r1.setRoleName("省管理员");
			roles.add(r1);
			Role r2 = new Role();
			r2.setRoleId("0056ee85505f40f399186cc724cdc7b2");
			r2.setRoleLevel(3);
			r2.setRoleName("省客户经理");
			roles.add(r2);
			Role r3 = new Role();
			r3.setRoleId("0056ee85505f40f399186cc724cdc7b5");
			r3.setRoleLevel(2);
			r3.setRoleName("市管理员");
			roles.add(r3);
			Role r4 = new Role();
			r4.setRoleId("0056ee85505f40f399186cc724cdc7b6");
			r4.setRoleLevel(3);
			r4.setRoleName("市客户经理");
			roles.add(r4);*/
			List<Role> roles2=null;
			User curuser=getCurrentUser(request);
			if(curuser.getRoleId().equals(ConstantUtils.RoleType.PGLY)){
				int[] levels={1,2,3,4};
				roles2=roleService.findByLevels(levels);
			}else{
				int[] levels={2,3,4};
				roles2=roleService.findByLevels(levels);
			}
			map.put("roles", roles2);
			
			map.put("code", HttpCode.HTTP_CODE_200);
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
	        map.put("msg", "获取用户信息失败");
		    log.error("获取用户信息失败",e);
		}
		if(jump==0){
			return "user/publicUpdate";	
		}else{
			return "user/userUpdate";
		}
		
	}
	/**
	 * 
	 * 方法含义：更改其他用户
		@author bgt
		@return 
		@date 2015-12-1
	 */
	@RequestMapping("/update")
    @ResponseBody
	public Map<String, Object> update(HttpServletRequest request,User user){
		Map<String, Object> map =  new HashMap<String, Object>();
		try {
			if(user !=null && StringUtils.isNotBlank(user.getUserId())){
				String newUrl=null;	
				if(StringUtils.isNotBlank(user.getHeadUrl())){
					newUrl = FileUtils.moveFile(request, "user_head", user.getHeadUrl());
					user.setHeadUrl(newUrl);
				}
				userService.updateByPrimaryKeySelective(user);
				map.put("code", HttpCode.HTTP_CODE_200);
				 map.put("msg", HttpCode.HTTP_MSG_200);
				if(StringUtils.isNotBlank(newUrl)){
					map.put("headUrl", newUrl);
				}
			}else{
				map.put("code", HttpCode.HTTP_CODE_400);
		        map.put("msg", HttpCode.HTTP_MSG_400);
		    }
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
	        map.put("msg", "更新用户信息失败");
		    log.error("更新用户信息失败",e);
		}
		return map;
	}
	
	@RequestMapping("/updateSelf")
	@ResponseBody
	public Map<String, Object> updateSelf(HttpServletRequest request,User user){
		Map<String, Object> map =  new HashMap<String, Object>();
		try {
			if(user !=null && StringUtils.isNotBlank(user.getUserId())){
				String newUrl=null;	
				if(StringUtils.isNotBlank(user.getHeadUrl())&&user.getHeadUrl().indexOf("user_head")==-1){
					newUrl = FileUtils.moveFile(request, "user_head", user.getHeadUrl());
					if(newUrl.equals("error")){
						map.put("code", HttpCode.HTTP_CODE_400);
						map.put("msg", "文件移到失败");
						return map;
					}
					user.setHeadUrl(newUrl);
				}
				userService.updateByPrimaryKeySelective(user);
				User newUser = userService.selectByPrimaryKey(user.getUserId());
				request.getSession().setAttribute(ConstantUtils.USERINFO, newUser);
				map.put("code", HttpCode.HTTP_CODE_200);
				if(StringUtils.isNotBlank(newUrl)){
					map.put("headUrl", newUrl);
				}
			}else{
				map.put("code", HttpCode.HTTP_CODE_400);
				map.put("msg", HttpCode.HTTP_MSG_400);
			}
		} catch (Exception e) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "更新用户信息失败");
			log.error("更新用户信息失败",e);
		}
		return map;
	}
	
	@RequestMapping("/userinfo")
	public String toUserinfoPage(HttpServletRequest request,ModelMap modelMap){
		try {
			User u = getCurrentUser2(request);
			User user = userService.selectByPrimaryKey(u.getUserId());
			modelMap.put("user", user);
			int level = 2;
			//2级区域
			List<AdminArea> adminAreas = adminAreaService.findAllByLevel(level);
			modelMap.put("adminAreas", adminAreas);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/personal/userinfo";
	}
	/**
	 * 
	 * 方法含义：去修改密码页面
		@author bgt
		@return 
		@date 2015-12-1
	 */
	@RequestMapping("/toUpdatePsw")
	public String toUpdatePsw(){
		return "/personal/password";
	}
}
